const multer = require("koa-multer");
const path = require("path");
const fs = require("fs");
const AppConfig = require("$config/app.config");

/**
 * 创建文件上传目录，如：当天不存在，则自动创建
 * @param {*} _baseDir
 */
const _createUploadFolder = _baseDir => {
	try {
		const now = new Date();
		const dayDir = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map(itm => (itm < 10 ? "0" + itm : itm)).join("");
		const fullPath = path.join(_baseDir, dayDir);
		fs.mkdirSync(fullPath, { recursive: true });
		console.log(`Directory created successfully at ${fullPath}`);
		return fullPath;
	} catch (error) {
		console.error(`Error creating directory: ${err.message}`);
		return null;
	}
};

/**
 * 创建文件名
 * @param {*} originFileName
 */
const _createFileName = originFileName => {
	const typeGroups = {
		ppt: ["ppt", "pptx"],
		xls: ["xls", "xlsx"],
		doc: ["doc", "docx"],
		image: ["jpg", "jpeg", "png", "gif", "bmp", "tiff"],
		pdf: ["pdf"],
		md: ["md"]
	};
	const fileSuffix = originFileName.includes(".") ? originFileName.split(".").pop() : originFileName;
	let str = "";
	for (const key in typeGroups) {
		if (typeGroups[key].includes(fileSuffix)) {
			str = key;
			break;
		}
	}
	return `${str || "file"}-${Date.now()}.${fileSuffix}`;
};

// 配置存储
const storage = multer.diskStorage({
	destination: function (req, file, cb) {
		const newFileFolderPath = _createUploadFolder(AppConfig.FILE_UPLOAD_PATH); // 创建文件夹
		if (newFileFolderPath === null) {
			return;
		}
		cb(null, newFileFolderPath); // 保存文件的目录
	},
	filename: function (req, file, cb) {
		const fileName = _createFileName(file.originalname);
		cb(null, fileName); // 文件名
	}
});

class UploadFile {
	// 上传实例
	_upload = multer({ storage: storage });

	// 单文件上传
	single(name = "file") {
		return this._upload.single(name);
	}

	// 多文件上传
	multiple() {}
}

module.exports = {
	uploadFile: new UploadFile()
};
